package com.go.where.family.api.servlet;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.go.where.family.api.constants.Constant;
import com.go.where.family.api.pojo.ActivityRetrospectInfo;
import com.go.where.family.api.scoket.Head;
import com.go.where.family.api.scoket.SocketDTO;
import com.go.where.family.api.scoket.TransmissionCode;
import com.go.where.family.api.server.HttpServerStartMain;
import com.go.where.family.api.utils.CommonUtil;
import com.go.where.family.api.utils.IpUtil;
import com.go.where.family.api.utils.MD5Util;
import com.go.where.family.api.utils.ServletUtil;
import com.go.where.family.api.vo.ActivityVo;
import com.go.where.family.api.vo.ResultVo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 获取家族活动回顾列表
 * 
 * @description
 * @author
 * @date
 */
public class GetActivityRetrospectsServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger
			.getLogger(GetActivityRetrospectsServlet.class);
	private static Gson gson = CommonUtil.gson();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);

		// 校验密文
		String sign = req.getParameter("sign");
		// 排序方式 1:最新，2：阅读量
		String sortType = req.getParameter("sortType");
		//
		String bigClassId = req.getParameter("bigClassId");
		String smallClassId = req.getParameter("smallClassId");
		String activityId = req.getParameter("activityId");
		// 第几页
		String pageIndex = req.getParameter("pageIndex");
		// 每页数目
		String pageCount = req.getParameter("pageCount");
		String customerId = req.getParameter("customerId");

		log.info("获取活动回顾列表：sign：" + sign + "，sortType：" + sortType + "，"
				+ "，bigClassId：" + bigClassId + "，smallClassId：" + smallClassId
				+ "，activityId：" + activityId + "，pageIndex：" + pageIndex
				+ "，pageCount：" + pageCount);

		boolean flag = this.validateData(sign, customerId, resp, req);
		if (flag) {// 数据校验成功
			boolean check = super.checkUser(req, resp);
			if (!check) {
				return;
			}
			try {
				ActivityVo vo = new ActivityVo();
				if (StringUtils.isNotBlank(pageIndex)
						&& StringUtils.isNotBlank(pageCount)) {
					vo.setPageIndex(Integer.parseInt(pageIndex));
					vo.setPageCount(Integer.parseInt(pageCount));
				}
				vo.setBigClassId(bigClassId);
				vo.setSmallClassId(smallClassId);
				vo.setActivityId(activityId);
				if (Constant.TIME_ORDER.equals(sortType)) {
					vo.setOrderBy("publish_time");
					vo.setOrderType(Constant.ORDER_TYPE_DESC);
				}
				if (Constant.BROWSE_NUM.equals(sortType)) {
					vo.setOrderBy("browse_num");
					vo.setOrderType(Constant.ORDER_TYPE_DESC);
				}
				SocketDTO dto = sendMessage(req, vo);
				Head head = dto.getHead();
				String resCode = head.getResponseCode();
				// String resMsg = head.getResponseMessage();
				String body = dto.getBody();
				if (TransmissionCode.SUCCESS.getCode().equals(resCode)) {
					// 把service中返回的信息转成对应的json格式字符串，返回给接口调用者
					if (StringUtils.isNotBlank(body)) {
						List<ActivityRetrospectInfo> actList = gson.fromJson(
								body,
								new TypeToken<List<ActivityRetrospectInfo>>() {
								}.getType());
						ResultVo ri = new ResultVo();
						ri.setCode(Constant.SUCCESS);
						ri.setStatus(Constant.TRUE);
						ri.setData(actList);
						ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
					} else {
						ServletUtil.writeErrorStr(resp);
					}
				} else {
					log.error("内部通信异常，" + head.getResponseMessage());
					ServletUtil.writeErrorStr(resp);
				}
			} catch (Exception e) {
				log.error("异常信息", e);
				// 异常情况，也把对应异常信息的json格式字符串返回给接口调用者
				ServletUtil.writeErrorStr(resp);
			}

		}
	}

	/**
	 * 向service服务发送请求
	 * 
	 * @param t
	 * @param req
	 * @return
	 */
	private SocketDTO sendMessage(HttpServletRequest req, ActivityVo vo) {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.GET_ACTIVITY_RETROSPECT_LIST);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId("api");
		return super.send(head, vo);
	}

	/**
	 * 数据校验合法性
	 * 
	 * @param id
	 * @param name
	 * @param sign
	 * @param resp
	 * @param req
	 * @return
	 * @throws IOException
	 */
	private boolean validateData(String sign, String customerId,
			HttpServletResponse resp, HttpServletRequest req)
			throws IOException {
		boolean result = false;
		ResultVo ri = new ResultVo();
		if (StringUtils.isEmpty(sign)) {
			log.info("签名字符串为空!!!");
			ri.setCode(Constant.SIGN_IS_NULL);
			ri.setStatus(Constant.FALSE);
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			return false;
		} else {
			String key = HttpServerStartMain.getValue("go.where.family.key");
			StringBuilder builder = new StringBuilder();
			builder.append("customerId");
			builder.append(customerId);
			builder.append("key");
			builder.append(key);

			String data = builder.toString();

			boolean checked = MD5Util.checkMD5Signature(data, sign);
			if (checked) {
				result = true;
			} else {
				log.info("数字签名失败！！！");
				ri.setCode(Constant.CHECK_SIGN_FAIL);
				ri.setStatus(Constant.FALSE);
				ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
				return false;
			}
		}

		return result;
	}

}
